package core.modules;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;


public class Messenger {
	
	private static PreparedStatement pps;
	private static String newThreadUID;
	
	public static String generateThreadUID() {
		return (newThreadUID = UUID.randomUUID().toString());
	}
	
	public static String fetchThreadUID()
	{
		return newThreadUID;
	}
	
	public static String writeMessageFile(){
		return fetchThreadUID().concat(".xml");
	}
	
	public static void postThread(int userId, String catalogNumber) {
		DatabaseConnector.setPreparedStatement
		("INSERT INTO  messaging (user_id ,hash, location, fileName, replyTo_threadId, isThread) VALUES " + "(?,?,?,?,?,?)");
		pps = DatabaseConnector.getPreparedStatement();
		
		try {
			pps.setInt(1, userId);
			pps.setString(2, generateThreadUID());
			pps.setString(3, catalogNumber);
			pps.setString(4, writeMessageFile());
			pps.setBoolean(6, true);
			pps.setInt(5, 0);

			pps.executeUpdate();
			System.out.println("You have started a new thread!");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void postReply(int userId, int threadId, String catalogNumber) {
		DatabaseConnector.setPreparedStatement
		("INSERT INTO  messaging (user_id ,hash, location, fileName, replyTo_threadId, isThread) VALUES " + "(?,?,?,?,?,?)");
		pps = DatabaseConnector.getPreparedStatement();
		
		try {
			pps.setInt(1, userId);
			pps.setString(2, generateThreadUID());
			pps.setString(3, catalogNumber);
			pps.setString(4, writeMessageFile());
			pps.setBoolean(6, false);
			pps.setInt(5, threadId);

			pps.executeUpdate();
			System.out.println("Thread was replied to.");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void deleteMessage(String hash) {
		DatabaseConnector.setPreparedStatement("DELETE from messaging WHERE hash = ?");
		pps = DatabaseConnector.getPreparedStatement();
		
		try {
			pps.setString(1, hash);
			System.out.println(pps.toString());
			pps.executeUpdate();
			System.out.println("Record deleted!");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
}